package com.cskaoyan.transfer;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 创建日期: 2022/04/22 10:00
 *
 * @author ciggar
 *
 * 转账的案例
 * 使用事务
 */
public class TransferDemo {

    public static void main(String[] args) {

        // 转账
        boolean ret = transfer("风华哥", "景天", 2000);

        if (ret) {
            System.out.println("转账成功！！！");
        }else {
            System.out.println("转账失败！！！");
        }

    }


    // 转账的方法
    public static boolean transfer(String fromName, String toName, Integer money) {

        Connection connection = JDBCUtils.getConnection();
        try {

            // 开启事务 (关闭事务的自动提交)
            connection.setAutoCommit(false);

            // 扣钱
            PreparedStatement preparedStatement = connection.prepareStatement("update account set money = money - ? where name = ?");

            // 赋值
            preparedStatement.setInt(1, money);
            preparedStatement.setString(2, fromName);

            int affectedRows = preparedStatement.executeUpdate();

            // 判断扣钱是否成功
            if (affectedRows < 1) {
                connection.rollback();
                return false;
            }



            // 加钱
            PreparedStatement preparedStatement2 = connection.prepareStatement("update account set money = money + ? where name = ?");

            // 赋值
            preparedStatement2.setInt(1, money);
            preparedStatement2.setString(2, toName);

            int affectedRows2 = preparedStatement2.executeUpdate();
            if (affectedRows2 < 1) return false;


            // 人为制造异常
            int i = 1 / 0;


            // 提交事务
            connection.commit();

        } catch (Exception ex) {
            ex.printStackTrace();

            // 回滚事务
            try {
                connection.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            return false;
        }

        return true;

    }

}
